# Copyright 2006 Michael Gorsuch <michael@styledbits.com>

# This file is part of GrabTheMic <http://www.grabthemic.org>.

# GrabTheMic is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA


class CommentController < ApplicationController
  
  before_filter :set_user
  before_filter :authorize, :only => [:create]
  
  layout "default"

  # GETs should be safe (see http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    if @user
      @votes = {}
      @user.votes.find(:all, :select => "story_id, value").each {|v| @votes[v.story_id] = v.value}
    end
    @story = Story.find(params[:id])
  end

  def create
    @comment = Comment.new(params[:comment])
    @story = Story.find(params[:id])
    @comment.story = @story
    @comment.user = @user
    if @comment.save
      AlertMailer.deliver_new_comment @comment unless (@comment.user == @story.user)
      flash[:notice] = 'Comment was successfully created.'
      redirect_to :action => 'list', :id => @comment.story.id
    else
      if @user
        @votes = {}
        @user.votes.find(:all, :select => "story_id, value").each {|v| @votes[v.story_id] = v.value}
      end
      render :action => 'list'
    end
  end

end
